// this is the new auth class that integrate with the jsonql-jwt
// all the auth related methods will be here
import { decodeToken } from 'jsonql-jwt'
import {
  CREDENTIAL_STORAGE_KEY,
  AUTH_HEADER,
  BEARER
} from 'jsonql-constants'
// chain
import ContractClass from './contract-cls'
// export
export default class AuthClass extends ContractClass {

  constructor(opts) {
    super(opts)
    if (opts.enableAuth && opts.useJwt) {
      this.setDecoder = decodeToken;
    }
  }

  /**
   * Getter to get the login userdata
   * @return {mixed} userdata
   */
  get userdata() {
    return this.jsonqlUserdata; // see base-cls
  }

  /**
   * Return the token from session store
   * @return {string} token
   */
  get rawAuthToken() {
    // this should return from the base
    return this.jsonqlToken; // see base-cls
  }

  /**
   * Setter to add a decoder when retrieve user token
   * @param {function} d a decoder
   */
  set setDecoder(d) {
    if (typeof d === 'function') {
      this.decoder = d;
    }
  }

  /**
   * Setter after login success
   * @TODO this move to a new class to handle multiple login
   * @param {string} token to store
   * @return {*} success store
   */
  storeToken(token) {
    return this.jsonqlToken = token;
  }

  /**
   * for overwrite
   * @param {string} token stored token
   * @return {string} token
   */
  decoder(token) {
    return token;
  }

  /**
   * Construct the auth header
   * @return {object} header
   */
  getAuthHeader() {
    const token = this.rawAuthToken;
    return token ? {[this.opts.AUTH_HEADER]: `${BEARER} ${token}`} : {};
  }

}
